import { useState } from 'react';
import { Popup, RadioGroup, Radio, Input, Button } from '@nutui/nutui-react-taro';
import { useSelector, useDispatch } from 'react-redux';
import { addTask, editTask, toggleEdit, clearEditTask } from '../../store/taskSlice.js';
import { TASK_STATUS } from '../../const/const.js';
import './EditDialog.scss';

export default function EditDialog(props) {
  const dispatch = useDispatch();
  const editTaskItem = useSelector(state => state.task.editTaskItem);
  const isEdit = useSelector(state => state.task.isEdit);
  const [radioVal, setRadioVal] = useState(editTaskItem ? editTaskItem.status : 'undo');
  const [title, setTitle] = useState(editTaskItem ? editTaskItem.title : '');
  // 更新任务名
  const UpdateTitleValue = function(val) {
    setTitle(val);
  }
  // 更新任务状态
  const UpdateStatusValue = function(val) {
    setRadioVal(val);
  }

  // 表单表单
  const submitTask = function() {
    console.log('--submitTask--', editTaskItem);
    if (!editTaskItem) {
      // 新增
      dispatch(addTask({
        item: {
          id: Date.now(),
          title,
          status: radioVal
        }
      }))
      closeEdit();
      return;
    }
    // 修改
    dispatch(editTask({
      item: {
        ...editTaskItem,
        title,
        status: radioVal
      }
    }))
    closeEdit();
  }

  /**
   * 关闭弹框
   */
  const closeEdit = function() {
    dispatch(toggleEdit({
      status: false
    }));
    setTimeout(() => {
      dispatch(clearEditTask());
      setRadioVal(TASK_STATUS.undo.key);
      setTitle('');
    }, 300)
  }
  return (
    <Popup
      closeable  
      visible={ isEdit } 
      style={{ height: '30%' }} 
      position="bottom" 
      onClose={ () => { closeEdit() } }
      popClass="edit-wrap"
    >
      <Input label="任务名：" defaultValue={editTaskItem ? editTaskItem.title : title}  placeholder="输入任务名" change={(val) => {
        UpdateTitleValue(val)
      }}/>
      <RadioGroup 
        style={{width:'100%', display: 'flex', justifyContent:'space-around', paddingTop: '10px', paddingBottom: '10px' }} 
        className='tast-status-toggle' 
        value={editTaskItem ? editTaskItem.status : radioVal} 
        direction="horizontal"
        onChange = {
          (value) => {
            UpdateStatusValue(value)
          }
        }
      >
        <Radio shape="button" value="undo">未开始</Radio>
        <Radio shape="button" value="doing">进行中</Radio>
        <Radio shape="button" value="done">已完成</Radio>
      </RadioGroup>
      <Button plain type="info" onClick={submitTask}>提交</Button>
    </Popup>
  )
}
